import cloneDeep from 'lodash/cloneDeep';
import router from '@/router'
import { constantRoute, asyncRoute, anyRoute } from '@/router/routes';
// import { user } from './user';
import { ref } from 'vue';


// 状态
// 0 初始化
// 1 请求中
// 2 请求完成
// 3 错误
let status = 0


// 处理异步路由
const filterUserRoute = (asyncRoute, route) => {
  return asyncRoute.filter(item => {
    if (item.children && item.children.length > 0) {
      // 有子路由的情况
      item.children = filterUserRoute(item.children, route)
      return true
    } else if (route.includes(item.name)) {
      // 没有子路由的情况
      return true
    }
  })
}

const getMenuhandle = async function () {
  try {
    status = 1
    // 计算当前用户的异步路由
    const userAsyncRoute = filterUserRoute(cloneDeep(asyncRoute), user.infoData.info?.routes)
    // 整合菜单路由，让菜单组件渲染菜单
    menu.infoData.value = [...constantRoute, ...userAsyncRoute, anyRoute]
    // 动态添加路由
    const routeTmp = [...userAsyncRoute, anyRoute]
    await routeTmp.forEach(route => router.addRoute(route))
    status = 2


  } catch (error) {
    status = 3
  }
}

const removeMenuhandle = async function () {
  status = 0
  // 整合菜单路由，让菜单组件渲染菜单
  menu.infoData.value = constantRoute
}

export const menu = {
  infoData: ref([]),
  async getInfo() {
    if (status !== 2) {
      await getMenuhandle()
    }
    return menu.infoData.value
  },
  resize() {
    removeMenuhandle()
  }
}